import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import axios from './utils/api'
import 'element-ui/lib/theme-chalk/index.css'
import 'echarts/theme/macarons'

Vue.use(ElementUI)

Vue.prototype.$axios = axios;

Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
    // 如果前端没有登录信息则直接拦截，如果有则判断后端是否正常登录（防止构造参数绕过）
    if (to.meta.requireAuth) {
        console.log('!!!' + JSON.stringify(store.getters.getUserDetails))
        const jsonData = JSON.parse(store.getters.getUserDetails)
        let sessionId = null
        if (jsonData != null) {
            sessionId = jsonData.sessionId.toString()
        }
        // 获取sessionId
        if (sessionId) { // 如果已登录
            // 判断是否是进入登录页面
            if (to.path.startsWith('/admin')) {
                initAdminMenu(router, store)
            }
            if (to.path.startsWith('/login')) {
                next({
                    name: 'Dashboard'
                })
            }
            if (to.name === 'login') {
                next('home')
            } else {
                next(true)
            }
        } else {
            axios.get('/api/getMe').then(
                function (response) {
                    if (response.data !== '') {
                        let user = response.data.data.user
                        if (user !== null) {
                            console.log(JSON.stringify(user.username))
                            // 登录成功后将sessionId 作为登录成功的标识
                            let userDetails = JSON.stringify(user)
                            store.commit('setUserDetails', userDetails)// 将userDetails存入vuex 中
                            console.log('  ++' + JSON.parse(store.getters.getUserDetails).sessionId)
                            sessionId = user.sessionId
                        }
                    }
                }
            ).catch(function (error) {
                console.log('服务器异常' + error)
            })
            if (sessionId) { // 如果已登录
                if (to.path.startsWith('/admin')) {
                    initAdminMenu(router, store)
                }
                if (to.path.startsWith('/login')) {
                    next({
                        name: 'Dashboard'
                    })
                }
                // 判断是否是进入登录页面
                if (to.name === 'login') {
                    next('home')
                } else {
                    next(true)
                }
            } else {
                next({
                    path: 'login',
                    query: {redirect: to.fullPath}
                })
            }
        }
    }
    next();
})

const initAdminMenu = (router, store) => {
    // 防止重复触发加载菜单操作
    if (store.state.adminMenus.length > 0) {
        return
    }
    axios.get('/api/menu/getMenus').then(resp => {
        if (resp && resp.status === 200) {
            var fmtRoutes = formatRoutes(resp.data.data.menus)
            router.addRoutes(fmtRoutes)
            store.commit('initAdminMenu', fmtRoutes)
        }
    })
}

const formatRoutes = (routes) => {
    let fmtRoutes = []
    routes.forEach(route => {
        if (route.children) {
            route.children = formatRoutes(route.children)
        }

        let fmtRoute = {
            path: route.path,
            component: resolve => {
                require(['./components/admin/' + route.component + '.vue'], resolve)
            },
            name: route.name,
            nameZh: route.nameZh,
            iconCls: route.iconCls,
            meta: {
                requireAuth: true
            },
            children: route.children
        }
        fmtRoutes.push(fmtRoute)
    })
    return fmtRoutes
}

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
